<template>
  <el-dialog @open="onDialogOpen" top="25vh"  :model-value="props.visible" @close="onClose" :title="t('flypass.set_pass')" width="600px">
    <el-form label-position="top">
      <el-form-item :label="t('modules.pass.pass_name')">
        <el-select v-model="topicId" class="w-full">
          <el-option v-for="item in topicList" :key="item.topicId" :value="item.topicId" :label="item.topicName"></el-option>
        </el-select>
      </el-form-item>
    </el-form>  
    <template #footer>
      <div class="text-right">        
        <el-button @click="onClose">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="confirm" :loading="loading">{{ t('common.confirm') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getTopicList, setMerchantTopic } from '@/api/topic/topic';
import { Topic } from '@/api/topic/topicModel';
import { ElMessage } from '@toms/element-ui';

const props = defineProps(['visible', 'mrchId', 'passId'])
const emit = defineEmits(['update:visible', 'save'])
const topicList = ref<Topic[]>([])
const topicId = ref<Topic['topicId'] | null>(null)
const loading = ref(false)
const { t } = useI18n()

async function onDialogOpen() {
  const { data } = await getTopicList({pageNo: 1, pageSize: 100}) 
  topicList.value = data
  topicId.value = props.passId
}

async function confirm() {
  if(topicId.value) {
    loading.value = true
    try {
      await setMerchantTopic({
        mrchId: props.mrchId,
        topicId: topicId.value
      })
    } catch(e: any) {
      ElMessage({
        type: 'error',
        message: e.message
      })
      loading.value = false
      return
    }    
    loading.value = false
    ElMessage({
      type: 'success',
      message: t('common.message.operation_success')
    })
    emit('save')
    emit('update:visible', false)
  }
}

function onClose() {
  topicId.value = null
  emit('update:visible', false)
}

</script>

<style></style>

